package pdf.genPDF;

import freemarker.template.Configuration;
import freemarker.template.Template;

import java.io.File;
import java.io.StringWriter;
import java.io.Writer;
import java.net.URL;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zgj
 * @create 2022-12-30 11:53
 * @discription 通过html模板生成html，转为pdf转换前的载体, 利用 freemarker
 */
public class GenPDFHelper {
    /**
     * 获取模板内容
     * @param templateDirectory 模板文件夹
     * @param templateName      模板文件名
     * @param paramMap          模板参数
     * @return HTML text        String
     * @throws Exception
     */
    static String getTemplateContent(String templateDirectory, String templateName, Map<String, Object> paramMap) throws Exception {
        Configuration configuration = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
        try {
            configuration.setDirectoryForTemplateLoading(new File(templateDirectory));
        } catch (Exception e) {
//            System.out.println("-- exception --");
            throw new Exception("获取HTML模板内容出错");
        }

        Writer out = new StringWriter();
        Template template = configuration.getTemplate(templateName,"UTF-8");
        template.process(paramMap, out);
        out.flush();
        out.close();
        return out.toString();
    }


    /**
     * useless
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        Map<String, Object> paramMap = new HashMap<>();
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        paramMap.put("date_time", dateTimeFormatter.format(LocalDateTime.now()));
        paramMap.put("date", dateTimeFormatter.format(LocalDateTime.now()).substring(0, 10));
        ClassLoader classLoader = GenPDFHelper.class.getClassLoader();
        URL resource = classLoader.getResource("templates");
        String templateDirectory  =resource.toURI().getPath();
        String templateContent = GenPDFHelper.getTemplateContent(templateDirectory, "test_template.html", paramMap);
        System.out.println(templateContent);
    }
}
